ViewModelBase = class('ViewModelBase')
require 'MVVM.Sources.Infrastructure.BindableProperty'
require 'MVVM.Sources.Infrastructure.CompoundBindableProperty'
function ViewModelBase:ctor()
    self._isInitialized = false
    self.ParentViewModel = nil
    self.IsRevealed = false
    self.timerCo = nil
    self.refreshDataTime = -1            --记录model刷新的时间，调用SetRefreshTime设置有效时间
    self.notifiedRefresh =false
    self.isShow =false
    self.needRefreshData = false
    self.firstShow = true           --是否第一次显示
end

function ViewModelBase:OnFirstShow()

end

function ViewModelBase:OnReveal()
    self.isShow = true
    if self.firstShow then
        self:OnFirstShow()
        self.firstShow = false
    end
    if self.needRefreshData and self.refreshDataTime == -1 then
        self.refreshDataTime = 1
    end
    self:SetRefreshTime(self.refreshDataTime)
end
function ViewModelBase:OnDestroy()
    self.isShow = false
end
function ViewModelBase:SetRefreshTime(refreshDataTime)

    self.refreshDataTime= refreshDataTime
    self.notifiedRefresh = false
    if refreshDataTime > 0 then
        if self.timerCo == nil then
            self.timerCo = self:StartCoroutine(function ()
                while(true) do
                    if self:CheckNeedRefreshData() then
                        self:OnRefreshData()
                        self.notifiedRefresh = true
                    end
                    coroutine.wait(1)
                end
            end)
        end
    end
end
function ViewModelBase:CheckNeedRefreshData()
    return  self.isShow and not self.notifiedRefresh and  self.refreshDataTime~= -1 and TimeModel.GetServerTime() >= self.refreshDataTime
end
function ViewModelBase:OnRefreshData()      --有效时间超过，1.界面打开时自动调用 2.处于当前界面时自动调用
end
function ViewModelBase:OnHide()
    self:ClearCoroutine()
end
function ViewModelBase:Destroy()
    self:ClearCoroutine()

    for i, attr in pairs(self) do
        if type(attr) == 'table' and attr.__cname == 'CompoundBindableProperty' then
            attr:Destroy()
        end
    end
    self.isShow = false
end


function ViewModelBase:StartCoroutine(func)
    if self.coroutines == nil then
        self.coroutines = {}
    end

    local co = coroutine.start(function()
        func()
        table.remove_value(self.coroutines, coroutine.running())
    end)
    table.insert(self.coroutines, co)

    return co
end

function ViewModelBase:StopCoroutine(co)
    if self.coroutines then
        table.remove_value(self.coroutines, co)
    end
    coroutine.stop(co)
end

function ViewModelBase:ClearCoroutine()
    if self.coroutines then
        for _, co in pairs(self.coroutines) do
            coroutine.stop(co)
        end
    end
    self.coroutines = {}
    self.timerCo = nil
end